package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sky.entity.Orders;
import com.sky.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class OrdersTask {
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private OrdersService ordersService;

    @Scheduled(cron = " 0 * * * * ? ")
    public void handleTimeOutOrders(){
        log.info("定时处理超时订单 {}", LocalDateTime.now().format(dateTimeFormatter));
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus, Orders.PENDING_PAYMENT)
                .lt(Orders::getOrderTime, LocalDateTime.now().minusMinutes(15))
                .select(Orders::getId);
        List<Long> list = ordersService.list(queryWrapper).stream().map(Orders::getId).collect(Collectors.toList());
        if(!list.isEmpty()){
            log.info("当前超时订单为 {}",list);
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                    .in(Orders::getId, list)
                    .set(Orders::getStatus, Orders.CANCELLED)
                    .set(Orders::getCancelReason, "订单超时")
                    .set(Orders::getCancelTime,LocalDateTime.now());
            ordersService.update(updateWrapper);
        }else {
            log.info("无超时订单");
        }
    }

    @Scheduled(cron = " 0 0 2 * * ? ")
    public void handleDeliveryOrders(){
        log.info("定时处理一直处于派送中的订单 {}",LocalDateTime.now().format(dateTimeFormatter));
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS)
                .lt(Orders::getOrderTime, LocalDateTime.now().minusHours(2));
        List<Long> list = ordersService.list(queryWrapper).stream().map(Orders::getId).collect(Collectors.toList());
        if(!list.isEmpty()) {
            log.info("当前订单一直处于派送中的订单为 {}", list);
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<Orders>()
                    .in(Orders::getId, list)
                    .set(Orders::getStatus, Orders.COMPLETED);
            ordersService.update(updateWrapper);
        }else {
            log.info("无一直处于派送中的订单");
        }
    }
}
